<template>
    <div id="user-register">
        <h2>注册账号</h2>
        <!--    rules： 关联校验规则
                 ref： 用户后期获取当前表单对象  判定校验规则是否满足
            -->
        <el-form :label-position="labelPosition" :model="user" :rules="rules" ref="ruleForm">
            <el-form-item prop="username">
                <el-input placeholder="用户名" v-model="user.username"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" placeholder="密码" v-model="user.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="registerUser" style="width: 100%">注册</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import {userRegister} from "@/api/user";

    export default {
        name: "RegisterView",
        data() {
            return {
                user: {
                    username: '',
                    password: ''
                },
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 6, max: 8, message: '长度在 6 到 8 个字符', trigger: 'blur'}
                    ]
                },
                labelPosition: "left"
            }
        },
        methods: {
            //  用户注册回调函数
            registerUser() {
                // TODO  将user信息提交到后台 写入数据库
                // 判定用户的数据是否符合要求
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {  // true

                        //异步请求技术  axios    http://localhost:9090/user/register
                        userRegister(this.user).then(resp => {
                            if (resp.code == 0) {  // 注册成功
                                this.$message.success(resp.message)
                                // 跳转页面到登录页
                                this.$router.push("/login")
                            } else {   // 注册失败
                                this.$message.error(resp.message)
                            }
                        })
                    } else {
                        this.$message.warning("请填写完整用户信息")
                        return false;
                    }
                });


            }
        }
    }
</script>

<style scoped>

    #user-register {
        width: 400px;
        height: 300px;
        margin: 0 auto;
        margin-top: 150px;
        text-align: center;
        color: #42b983;
    }
</style>
